﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Windows.Forms;
using Z16.BLI;

namespace Z16.SITE
{
    public partial class RelatorioHorasCC : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((Session["CodPerfil"] == null) || (Session["CodUsr"] == null))
            {
                Response.Write("<script>window.location=\'Login.aspx';</script>");
                return;
            }

            if (!IsPostBack)
            {
                carregarCentroCusto();
                Chart1.Visible = false;
                Chart2.Visible = false;
            }
        }

        private void carregarCentroCusto()
        {
            CentroDeCusto centroCusto = new CentroDeCusto();

            ddlCentroCusto.Items.Clear();
            ddlCentroCusto.AppendDataBoundItems = true;
            ddlCentroCusto.Items.Insert(0, "SELECIONE");

            ddlCentroCusto.DataSource = centroCusto.ListarCentroCustoAtivo();
            ddlCentroCusto.DataValueField = "Cod_Centro_De_Custo";
            ddlCentroCusto.DataTextField = "Nome_Centro_De_Custo";
            ddlCentroCusto.DataBind();
        }

        protected void btnGerar_Click(object sender, EventArgs e)
        {
            if (!ValidaCampos())
                return;

            int? CodCentroCusto = null;
            if (ddlCentroCusto.SelectedIndex > 0)
                CodCentroCusto = Convert.ToInt32(ddlCentroCusto.SelectedValue);

            CentroDeCusto centroDeCusto = new CentroDeCusto();
            var listaAllCC = centroDeCusto.ListarCentroDeCustoID(CodCentroCusto);

            var dtIniPro = String.Format("{0:ddMMyyyy}", DateTime.Parse(txtDataIni.Text));
            var dtFinPro = String.Format("{0:ddMMyyyy}", DateTime.Parse(txtDataFim.Text));

            CentroDeCusto TotalHorasCC = new CentroDeCusto();
            var listaTotalHorasCC = TotalHorasCC.TotalHorasCentroDeCusto(dtIniPro, dtFinPro);

            pnlRelatorio.Controls.Add(new LiteralControl("<table bgcolor =\'#000000\' border=\'0\' cellppading =\'1\'  cellspacing=\'1\' style=\"width: 100%\">"));
            pnlRelatorio.Controls.Add(new LiteralControl("<TR>"));
            pnlRelatorio.Controls.Add(new LiteralControl("<TD> <BR /> </TD>"));
            pnlRelatorio.Controls.Add(new LiteralControl("</TR>"));
            pnlRelatorio.Controls.Add(new LiteralControl("<tr bgcolor=\"#473C8B\">"));
            pnlRelatorio.Controls.Add(new LiteralControl("<td colspan=\'2\'><font color=\'white\'>TOTAL HORAS DESENVOLVIMENTO</font></td>"));
            pnlRelatorio.Controls.Add(new LiteralControl("<td align=\"center\"><font color=\'white\'> TOTAL HORAS: " + listaTotalHorasCC.Rows[0]["TOTAL_MIUTO_CCs"] + "</font></td>"));
            pnlRelatorio.Controls.Add(new LiteralControl("</tr>"));

            string corFundo = "";

            pnlRelatorio.Controls.Add(new LiteralControl("<TR bgcolor=\"#836FFF\">"));
            pnlRelatorio.Controls.Add(new LiteralControl("<TD align=\"center\"><font color=\'white\'>CENTRO DE CUSTO</TD>"));
            pnlRelatorio.Controls.Add(new LiteralControl("<TD align=\"center\"><font color=\'white\'>HORAS"));
            pnlRelatorio.Controls.Add(new LiteralControl("<TD align=\"center\"><font color=\'white\'>%</TD>"));
            pnlRelatorio.Controls.Add(new LiteralControl("</TR>"));

            var totalHorasUser = Convert.ToInt32(listaTotalHorasCC.Rows[0]["TOTAL_MIUTO_CC"]);
            
            var dtGrafico = new DataTable();
            dtGrafico.Columns.Add(new DataColumn("NOME_CENTRO_DE_CUSTO"));
            dtGrafico.Columns.Add(new DataColumn("TOTAL_MIUTO_CENTROCUSTO"));
            dtGrafico.Columns.Add(new DataColumn("TotMin"));
            dtGrafico.Columns.Add(new DataColumn("Porcent"));

            for (int j = 0; j < listaAllCC.Rows.Count; j++)
            {
                var codCC = Convert.ToInt32(listaAllCC.Rows[j]["Cod_Centro_De_Custo"]);

                var HorasCC = new CentroDeCusto();
                var listaHorasUsercc = HorasCC.HorasCentroDeCustoId(codCC, totalHorasUser, dtIniPro, dtFinPro);

                corFundo = corFundo == "#D7E2E8" ? "#FFFFFF" : "#D7E2E8";

                pnlRelatorio.Controls.Add(new LiteralControl("<TR bgcolor=\'" + corFundo + "\'>"));
                pnlRelatorio.Controls.Add(new LiteralControl("<TD>" + listaAllCC.Rows[j]["NOME_CENTRO_DE_CUSTO"] + "</TD>"));
                pnlRelatorio.Controls.Add(new LiteralControl("<TD align=\"center\">" + listaHorasUsercc.Rows[0]["TOTAL_MIUTO_CENTROCUSTO"] + "</TD>"));
                pnlRelatorio.Controls.Add(new LiteralControl("<TD align=\"center\">" + listaHorasUsercc.Rows[0]["PORCENTAGEM_CENTRO_CUSTO"] + "</TD>"));
                pnlRelatorio.Controls.Add(new LiteralControl("</TR>"));

                //Aqui
                DataRow row = dtGrafico.NewRow();
                row["NOME_CENTRO_DE_CUSTO"] = listaAllCC.Rows[j]["NOME_CENTRO_DE_CUSTO"].ToString();
                row["TOTAL_MIUTO_CENTROCUSTO"] = listaHorasUsercc.Rows[0]["TOTAL_MIUTO_CENTROCUSTO"].ToString();
                row["TotMin"] = listaHorasUsercc.Rows[0]["TotMin"].ToString();
                row["Porcent"] = Convert.ToDouble(listaHorasUsercc.Rows[0]["PORCENTAGEM_CENTRO_CUSTO"].ToString());

                dtGrafico.Rows.Add(row);
            }
            pnlRelatorio.Controls.Add(new LiteralControl("<TR>"));
            pnlRelatorio.Controls.Add(new LiteralControl("<TD> <BR /> </TD>"));
            pnlRelatorio.Controls.Add(new LiteralControl("</TR>"));
            pnlRelatorio.Controls.Add(new LiteralControl("</table>"));

            //Gera Gráfico Horas por Centro de Custo
            GenerateChart(Chart1, dtGrafico);
            Chart1.Visible = true;

            //Gera Gráfico Porcentagem por Centro de Custo
            GenerateChartPorcet(Chart2, dtGrafico);
            Chart2.Visible = true;
        }

        private Boolean ValidaCampos()
        {
            if (txtDataIni.Text == "" || txtDataFim.Text == "")
            {
                MessageBox.Show("Informe o período da pesquisa.", "Data Inválida.", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            return true;
        }


        public void GenerateChart(Chart currentChart,DataTable dtGrafico)
        {
            ChartComponents Components = new ChartComponents();

            List<double> yValues = new List<double>();
            List<string> xValues = new List<string>();

            currentChart.Series.Add(Components.CreateSeriesColumnControl("Disabled"));//Disabled, Inside, Outside 

            for (int i = 0; i < dtGrafico.Rows.Count; i++)
            {
                decimal totHoras = 0;

                if (dtGrafico.Rows[i]["TotMin"].ToString() != "")
                {
                    totHoras = decimal.Parse(dtGrafico.Rows[i]["TotMin"].ToString()) / 60;
                    totHoras = decimal.Round(totHoras,2);
                }
  
                yValues.Add(double.Parse(totHoras.ToString()));
                xValues.Add(dtGrafico.Rows[i]["NOME_CENTRO_DE_CUSTO"].ToString());
            }

            currentChart.ChartAreas.Add(Components.CreateChartArea(0));
            currentChart.Series["Default"].Points.DataBindXY(xValues, yValues);
            currentChart.Width = Components.CreateChartWidth(500);
            currentChart.Height = Components.CreateChartHeight(300);
            currentChart.Series[0].IsValueShownAsLabel = true;
            currentChart.Series[0]["PointWidth"] = "0.5";
            currentChart.Titles.Add("Horas por Centro de Custo");

            currentChart.DataBind();
        }

        public void GenerateChartPorcet(Chart currentChart, DataTable dtGrafico)
        {
            ChartComponents Components = new ChartComponents();

            List<double> yValues = new List<double>();
            List<string> xValues = new List<string>();

            currentChart.Series.Add(Components.CreateSeriesColumnControl("Disabled"));//Disabled, Inside, Outside 

            for (int i = 0; i < dtGrafico.Rows.Count; i++)
            {

                yValues.Add(double.Parse(dtGrafico.Rows[i]["PORCENT"].ToString()));
                xValues.Add(dtGrafico.Rows[i]["NOME_CENTRO_DE_CUSTO"].ToString());
            }

            currentChart.ChartAreas.Add(Components.CreateChartArea(0));
            currentChart.Series["Default"].Points.DataBindXY(xValues, yValues);
            currentChart.Width = Components.CreateChartWidth(500);
            currentChart.Height = Components.CreateChartHeight(300);
            currentChart.Series[0].IsValueShownAsLabel = true;
            currentChart.Series[0]["PointWidth"] = "0.5";
            currentChart.Titles.Add("Porcentagem por Centro de Custo");

            currentChart.DataBind();
        }

        public Chart CreateChartControl()
        {
            Chart chart = new Chart();
            return chart;
        }

        public class ChartData
        {
            public string X { get; set; }

            public double Y { get; set; }

            public string Legend { get; set; }
        }
    }
}